package com.sunny.webflux.webclient;

import javafx.geometry.VPos;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 使用WebClient开发响应式Http客户端
 *
 * @author sunny
 * @date 2018/11/30
 */
public class WebClientTest {


    @Test
    public void webClientTest1() throws InterruptedException {
        WebClient webClient = WebClient.create("http://127.0.0.1:9091");
        Mono<String> body = webClient.get().uri("/date").retrieve().bodyToMono(String.class);

        body.subscribe(System.out::println);

        TimeUnit.SECONDS.sleep(1);
    }

    @Test
    public void webClientTest2() {
        WebClient webClient = WebClient.builder().baseUrl("http://127.0.0.1:9090").build();
        webClient.get().uri("/noPer/users/queryUserById/1")
                .accept(MediaType.APPLICATION_STREAM_JSON)
                .exchange()
                .flatMapMany(response -> response.bodyToFlux(Map.class))
                .doOnNext(System.out::println)
                .blockLast();
    }

    @Test
    public void webClientTest3() throws InterruptedException {
        WebClient webClient = WebClient.create("http://127.0.0.1:9091");
        webClient
                .get().uri("/times")
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(String.class)
                .log()
                .take(10)
                .blockLast();
    }
}
